package com.dwj.auto.comment.common.utils;

import com.dwj.auto.comment.config.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;


/**
 * @author: dangweijian
 * @description: 编号生成器
 * @create: 2020-01-15 22:49
 **/
public class CodeUtil {

    private static RedisTemplate<String, Object> redisTemplate;

    private static synchronized RedisTemplate<String, Object> getRedisTemplate(){
        if(redisTemplate == null){
            redisTemplate = SpringUtil.getBean("redisTemplate");
        }
        return redisTemplate;
    }

    public static String generateCode(String domain, String prefix, int digit) {
        if(StringUtils.isEmpty(domain)){
            throw new BusinessException("domain can not be empty!");
        }
        if(digit <= 0){
            throw new BusinessException("digit must be greater than zero!");
        }
        if(StringUtils.isNotEmpty(prefix)){
            prefix = StringUtils.join(prefix, "_");
        }
        Long incr = getRedisTemplate().opsForValue()
                .increment(StringUtils.join(domain.replaceAll(":",""), ":", domain,"_", prefix, digit));
        String code = String.format("%0" + digit + "d", incr);
        return StringUtils.join(prefix, code);
    }

    public static String generateCode(String domain, int digit) {
        return generateCode(domain, null, digit);
    }

    public static String uuid(){
        return UUID.randomUUID().toString().replaceAll("-","").toLowerCase();
    }

    public static String createUsername(){
        int prefix = (int)(Math.random()*900)+100;
        Long num = getRedisTemplate().opsForValue().increment("username_rand_num");
        String suffix = String.valueOf(System.currentTimeMillis());
        suffix = suffix.substring(suffix.length() - 4, suffix.length() - 1);
        return "" + prefix + num + suffix;
    }

    public static String createPassword(int digits){
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder password = new StringBuilder();
        for (int i = 0; i < digits; i++) {
            char c = chars.charAt((int) (Math.random() * chars.length()));
            password.append(c);
        }
        return password.toString();
    }
}
